package com.xunlai.infra.permission.business.service.impl;

import com.xunlai.infra.permission.business.converter.AdPictureConverter;
import com.xunlai.infra.permission.business.dao.entity.AdPicture;
import com.xunlai.infra.permission.business.dao.repository.AdPictureRepository;
import com.xunlai.infra.permission.business.service.AdPictureService;
import com.xunlai.infra.permission.business.vo.ad.AdPictureCreateVo;
import com.xunlai.infra.permission.business.vo.ad.AdPictureListVo;
import com.xunlai.infra.permission.common.vo.BasePageRespVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * @author liang
 * @date 9/25/23 9:34 PM
 */
@Service
public class AdPictureServiceImpl implements AdPictureService {

    private AdPictureRepository adPictureRepository;

    @Override
    public Long createAdPicture(AdPictureCreateVo adPictureCreateVo) {
        AdPicture adPicture = AdPictureConverter.INSTANCE.convertCreateVo2Entity(adPictureCreateVo);
        adPicture.setActive(false);
        AdPicture save = adPictureRepository.save(adPicture);
        return save.getId();
    }

    @Override
    public void deleteAdPicture(Long id) {
        adPictureRepository.deleteById(id);
    }

    @Override
    public BasePageRespVo<AdPictureListVo> listAdPicture(Integer pageNum, Integer pageSize) {
        pageNum = (pageNum == null || pageNum < 1) ? 1 : pageNum;
        int size = (pageSize == null || pageSize <= 0) ? 10 : pageSize;
        PageRequest pageRequest = PageRequest.of(pageNum -1 ,size);
        Page<AdPicture> picturePage = adPictureRepository.findAll(pageRequest);
        List<AdPictureListVo> adPictureListVos = picturePage.getContent().stream().map(AdPictureConverter.INSTANCE::convertEntity2ListVo).toList();
        return new BasePageRespVo<>(adPictureListVos,pageNum,pageSize,picturePage.getTotalElements(), picturePage.getTotalPages());
    }

    @Override
    public List<AdPictureListVo> listAllActiveAdPicture() {
        List<AdPicture> allByActive = adPictureRepository.findAllByActive(true);
        return allByActive.stream().map(AdPictureConverter.INSTANCE::convertEntity2ListVo).toList();
    }

    @Override
    public void changeActiveStatus(Long id,boolean active) {
        Optional<AdPicture> adPictureOptional = adPictureRepository.findById(id);
        if(adPictureOptional.isEmpty()){
            return;
        }
        AdPicture adPicture = adPictureOptional.get();
        adPicture.setActive(active);
        adPictureRepository.save(adPicture);
    }

    @Autowired
    public void setAdPictureRepository(AdPictureRepository adPictureRepository) {
        this.adPictureRepository = adPictureRepository;
    }
}
